using System;
using System.Collections;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;

namespace UnityX
{
    public static class WeChat
    {
        public const string AndroidAppId = "";
        public const string AndroidAppSecret = "";

        public const string iOSAppId = "";
        public const string iOSAppSecret = "";
        public const string iOSUniversalLink = "";

        [Serializable]
        public class AccessToken
        {
            public string access_token = "ACCESS_TOKEN";
            public int expires_in = 7200;
            public string refresh_token = "REFRESH_TOKEN";
            public string openid = "OPENID";
            public string scope = "SCOPE";
            public string unionid = "o6_bmasdasdsad6_2sgVt7hMZOPfL";
        }
        [Serializable]
        public class Userinfo
        {
            public string openid = "OPENID";
            public string nickname = "NICKNAME";
            public int sex = 1;
            public string province = "PROVINCE";
            public string city = "CITY";
            public string country = "COUNTRY";
            public string headimgurl = @"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0";
            public string[] privilege = new string[] { "PRIVILEGE1", "PRIVILEGE2" };
            public string unionid = "o6_bmasdasdsad6_2sgVt7hMZOPfL";
        }

#if UNITY_IOS
        [DllImport("__Internal")]
        private static extern void Auth(string appId, string universalLink);
        [DllImport("__Internal")]
        private static extern int GetState();
        [DllImport("__Internal")]
        private static extern string GetResult();
#endif

        public static void GetAccessToken(Action<AccessToken> actoin)
        {
            //UnityLoop.StartCoroutine(AccessTokenResult(actoin));
        }
        public static void GetUserinfo(Action<Userinfo> actoin)
        {
            //UnityLoop.StartCoroutine(UserinfoResult(actoin));
        }
        public static void GetHeadimg(string headimgurl, Action<Texture2D> actoin)
        {
            //UnityLoop.StartCoroutine(HeadimgResult(headimgurl, actoin));
        }
        private static IEnumerator AccessTokenResult(Action<AccessToken> actoin)
        {
            int state = 0;
            string result = "超时";
#if UNITY_ANDROID
            AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            AndroidJavaClass WXEntryActivity = new AndroidJavaClass("com.xq.hhl.wxapi.WXEntryActivity");
            WXEntryActivity.SetStatic("APP_ID", AndroidAppId);
            WXEntryActivity.CallStatic("Auth", currentActivity);
            for (int i = 0; i < 3000; i++)
            {
                state = WXEntryActivity.GetStatic<int>("State");
                if (state != 1)
                {
                    result = WXEntryActivity.GetStatic<string>("Result");
                    break;
                }
                yield return 0.1f;
            }
#elif UNITY_IOS
        Auth(AppId, UniversalLink);
        for (int i = 0; i < 3000; i++)
        {
            state = GetState();
            if (state != 1)
            {
                result = GetResult();
                break;
            }
            yield return 0.1f;
        }
#endif
            if (state != 2)
            {
                Debug.LogError(result);
                actoin(null);
                yield break;
            }
            AccessToken accessToken = null;
            using (UnityWebRequest webRequest = UnityWebRequest.Get(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AndroidAppId + "&secret=" + AndroidAppSecret + "&code=" + result + "&grant_type=authorization_code"))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    string text = webRequest.downloadHandler.text;
                    try
                    {
                        accessToken = JsonUtility.FromJson<AccessToken>(text);
                    }
                    catch
                    {
                        Debug.LogError("通过 Code 获取 AccessToken 出错");
                    }
                }
                else
                {
                    Debug.LogError("通过 Code 获取 AccessToken 出错");
                }
            }
            actoin(accessToken);
        }
        private static IEnumerator UserinfoResult(Action<Userinfo> actoin)
        {
            int state = 0;
            string result = "超时";
#if UNITY_ANDROID
            AndroidJavaClass UnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject currentActivity = UnityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
            AndroidJavaClass WXEntryActivity = new AndroidJavaClass("com.xq.hhl.wxapi.WXEntryActivity");
            WXEntryActivity.SetStatic("APP_ID", AndroidAppId);
            WXEntryActivity.CallStatic("Auth", currentActivity);
            for (int i = 0; i < 3000; i++)
            {
                state = WXEntryActivity.GetStatic<int>("State");
                if (state != 1)
                {
                    result = WXEntryActivity.GetStatic<string>("Result");
                    break;
                }
                yield return 0.1f;
            }
#elif UNITY_IOS
        Auth(AppId, UniversalLink);
        for (int i = 0; i < 3000; i++)
        {
            state = GetState();
            if (state != 1)
            {
                result = GetResult();
                break;
            }
            yield return 0.1f;
        }
#endif
            if (state != 2)
            {
                Debug.LogError(result);
                actoin(null);
                yield break;
            }
            AccessToken accessToken = null;
            using (UnityWebRequest webRequest = UnityWebRequest.Get(@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AndroidAppId + "&secret=" + AndroidAppSecret + "&code=" + result + "&grant_type=authorization_code"))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    string text = webRequest.downloadHandler.text;
                    try
                    {
                        accessToken = JsonUtility.FromJson<AccessToken>(text);
                    }
                    catch
                    {
                        Debug.LogError("通过 Code 获取 AccessToken 出错");
                    }
                }
                else
                {
                    Debug.LogError("通过 Code 获取 AccessToken 出错");
                }
            }

            Userinfo userinfo = null;
            using (UnityWebRequest webRequest = UnityWebRequest.Get(@"https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken.access_token + "&openid=" + accessToken.openid))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    string text = webRequest.downloadHandler.text;
                    try
                    {
                        userinfo = JsonUtility.FromJson<Userinfo>(text);
                    }
                    catch
                    {
                        Debug.LogError("通过 AccessToken 获取 Userinfo 出错");
                    }
                }
                else
                {
                    Debug.LogError("通过 AccessToken 获取 Userinfo 出错");
                }
            }
            actoin(userinfo);
        }

        private static IEnumerator HeadimgResult(string headimgurl, Action<Texture2D> actoin)
        {
            Texture2D texture2D = null;
            using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(headimgurl))
            {
                yield return webRequest.SendWebRequest();
                if (webRequest.result == UnityWebRequest.Result.Success)
                {
                    texture2D = DownloadHandlerTexture.GetContent(webRequest);
                }
                else
                {
                    Debug.LogError(webRequest.error);
                }
            }
            actoin(texture2D);
        }
    }
}